/*
 * atmega_adc.c
 *
 * Created: 4/4/2011 17:03:26
 *  Author: morpheus
 */ 
#include <stdlib.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/portpins.h>


#ifndef F_CPU
#define F_CPU 16000000UL
#endif
#include <util/delay.h>

#include "uart.h"

#define US_PORT PORTA
#define US_PIN   PINA
#define US_DDR    DDRA

#define US_POS PA0

#define clockCyclesPerMicroseconds() (F_CPU / 1000000UL)
#define clockCyclesToMicroseconds(a) ((a) / clockCyclesPerMicroseconds())
#define microsecondsToClockCycles(a) ((a) * clockCyclesPerMicroseconds())

uint16_t pulse(uint8_t _PORT, uint8_t pin);

int  main()
{
  uint16_t distance = 0;
  char buffer[20];
  uart_init();
  _delay_ms(2000);


  // PORTD 2 will be the ranging port
  //Set Ultra Sonic Port as input
  DDRD |= (0 << PIN2);

  uart_puts("Starting serial\r\n");
  

  
  while(1)
  {



    _delay_ms(250);

    //Measure the width of pulse
    distance = pulse(PORTB, PIN2);

    ltoa(distance, buffer, 10);
    uart_puts(distance);
    uart_putc('\r');
    uart_putc('\n');

  }

  return 0;
}

/*
 * Check for pulse high. It will wait until the pin
 * is set high then wait until the pin goes low. This
 * should give us an ok timing or close enough.
 */
uint16_t pulse(uint8_t _PORT, uint8_t pin)
{
  uint16_t width = 0;
  uint16_t MAXLOOPS = 0;
 

  // start critical area timing
  // loop until the pin is set
  loop_until_bit_is_set(_PORT, pin);
  
  // loop uitl the pin is clear
  while(bit_is_clear(_PORT, pin))
  {
    ++width;
  }
  

  return clockCyclesToMicroseconds(width * 10 + 16);
}
